package com.laikan.reader.article.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.facebook.drawee.view.SimpleDraweeView;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.managers.ToastMgr;
import com.laikan.reader.R;
import com.laikan.reader.article.adapter.FocusReplyAdapter;
import com.laikan.reader.article.requester.FocusReplyDetailRequester;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.core.LaikanApplication;
import com.laikan.reader.core.bean.FocusReplyDetailBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.SnackBarNotice;
import com.laikan.reader.core.view.TipInfoLayout;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by Administrator on 2016/11/8.
 */
public class FocusCommentDetailActivity extends BasicActivity {
    //1代表评论类型的赞，2代表文章类型的赞
    public static final int CLICKTOSUPPORT_TYPE = 1;
    private static final int PAGE_SIZE = 10;
    private ArrayList<FocusReplyDetailBean.ReplyListData> mReplyDataList;
    private HashSet mReplyIdList = new HashSet();
    private FocusReplyAdapter articleReplyAdapter;
    private FocusReplyDetailBean.FocusReplyObjectDetail headData;
    private String replyId, comment;

    private ListView comment_detail_listview;
    private View head_view, footer_view;
    private RelativeLayout back_layout, rl_clicktosupport, bottom_layout;
    private ProgressBar_Modern progressbar_modern;
    private TouchSwipeRefreshLayout common_swiperefresh;
    private LoadingDialog mloadingDialog;
    private TipInfoLayout tipinfo;
    private ImageView iv_back, iv_clicktosupport;
    private Button send_btn;
    private EditText comment_edit;

    private boolean mIsClickToSupportSuccess = true;
    private boolean mIsInitRequestData = true;
    private int mCurrentPage = 1;
    private int END_LIST_PAGE = -1;

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_comment_detail);
        common_swiperefresh = (TouchSwipeRefreshLayout)findViewById(R.id.common_swiperefresh);
        common_swiperefresh.setColorSchemeResources(R.color.C_66ccdd);
        comment_detail_listview = (ListView)findViewById(R.id.comment_detail_listview);
        comment_edit = (EditText)findViewById(R.id.comment_edit);
        send_btn = (Button)findViewById(R.id.send_btn);
        tipinfo = (TipInfoLayout)findViewById(R.id.tip_info);
        progressbar_modern = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        bottom_layout = (RelativeLayout)findViewById(R.id.bottom_layout);

        head_view = View.inflate(mContext, R.layout.lk_comment_head, null); // 头布局
        footer_view = View.inflate(mContext, R.layout.lk_comment_foot_view, null); // 脚布局
        comment_detail_listview.addHeaderView(head_view);
        comment_detail_listview.addFooterView(footer_view);
        iv_back = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
    }

    @Override
    protected void initData() {
        openEventBus();
        footer_view.setVisibility(View.GONE);
        common_swiperefresh.setEnabled(false);
        mloadingDialog = new LoadingDialog(mContext);
        BitmapDrawable drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back_tv);
        mReplyDataList = new ArrayList<>();
        articleReplyAdapter = new FocusReplyAdapter(mContext, mReplyDataList);
        replyId = getIntent().getStringExtra("replyId");
        comment_detail_listview.setAdapter(articleReplyAdapter);
        requestNetData();
    }

    private void requestNetData() {
        if (mIsInitRequestData) {
            tipinfo.setLoading();
            FocusReplyDetailRequester.getReplayList(mCurrentPage, replyId, common_swiperefresh);
        }
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        switch (event.getEventID()) {
            case LaiKanEvent.EVENT_ID_GET_REPLY_LIST:
                mIsInitRequestData = false;
                FocusReplyDetailBean result = (FocusReplyDetailBean)event.getElves();
                headData = result.getFocusReplyData().getFocusReplyDetailData();
                if (mCurrentPage == 1) {
                    articleReplyAdapter.setDatas(updateListData(result.getFocusReplyData().getReplyList()));
                }else {
                    articleReplyAdapter.setDatas(loadMoreData(result.getFocusReplyData().getReplyList()));
                }
                articleReplyAdapter.setDatas(mReplyDataList);
                mCurrentPage = mReplyDataList.size() / PAGE_SIZE + 1;
                if (result.getFocusReplyData().getReplyList().size() < 10) {
                    mCurrentPage = END_LIST_PAGE;
                }
                tipinfo.setHide();
                progressbar_modern.setHide();
                setView();
                break;
            case LaiKanEvent.EVENT_ID_ARTICLE_SEND_REPLY:
                mCurrentPage = 1;
                FocusReplyDetailRequester.getReplayList(mCurrentPage, replyId, common_swiperefresh);
                comment_edit.setText("");
                break;
            case LaiKanEvent.EVENT_ID_COMMENT_NOTIC:
                progressbar_modern.setHide();
                if (mIsInitRequestData) {
                    tipinfo.setLoadError(R.string.laikan_data_load_failed);
                }else {
                    ToastMgr.showLongToast(R.string.laikan_network_anomaly);
                }
                break;
/*            case LaiKanEvent.EVENT_ID_SHOW_NOTICE:
                SnackBarNotice.customSnackbarShow(comment_detail_listview, event.getEventAction());
                break;*/
            case LaiKanEvent.EVENT_ID_FOCUS_REFRESH_REPLY_NUMBER:
                mIsClickToSupportSuccess = true;
                break;
            default:
                break;
        }
    }

    private ArrayList<FocusReplyDetailBean.ReplyListData> updateListData(List<FocusReplyDetailBean.ReplyListData> list) {
        ArrayList<FocusReplyDetailBean.ReplyListData> refreshList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (!mReplyIdList.contains(list.get(i).getObjectId())) {
                mReplyIdList.add(list.get(i).getObjectId());
                refreshList.add(list.get(i));
            }
        }
        refreshList.addAll(mReplyDataList);
        mReplyDataList.clear();
        mReplyDataList.addAll(refreshList);
        refreshList.clear();
        return mReplyDataList;
    }

    private ArrayList<FocusReplyDetailBean.ReplyListData> loadMoreData(List<FocusReplyDetailBean.ReplyListData> list) {
        for (int i = 0; i < list.size(); i++) {
//            if (!mReplyIdList.contains(list.get(i).getObjectId())) {
                mReplyIdList.add(list.get(i).getObjectId());
                mReplyDataList.add(list.get(i));
//            }
        }
        return mReplyDataList;
    }

    /**
     * 数据处理，ui展示
     */
    private void setView() {
        SimpleDraweeView head_reviewer_img = (SimpleDraweeView)head_view.findViewById(R.id.head_reviewer_img);
        TextView head_reviewer_name = (TextView)head_view.findViewById(R.id.head_reviewer_name);
        ImageView comment_image_jing = (ImageView)head_view.findViewById(R.id.comment_imge_jing);
        //        comment_image_jing.setVisibility(View.GONE);
        TextView head_comment_time = (TextView)head_view.findViewById(R.id.head_comment_time);
//        TextView comment_title = (TextView)head_view.findViewById(R.id.comment_title);
        TextView head_comment_content = (TextView)head_view.findViewById(R.id.head_comment_content);
        //看点评论列表添加头部点赞功能
        rl_clicktosupport = (RelativeLayout)head_view.findViewById(R.id.rl_clicktosupport);
        rl_clicktosupport.setVisibility(View.VISIBLE);
        rl_clicktosupport.setOnClickListener(this);
        TextView tv_clicktosupport = (TextView)head_view.findViewById(R.id.tv_clicktosupport);
        iv_clicktosupport = (ImageView)head_view.findViewById(R.id.iv_clicktosupport);

        if (headData.isPraise()) {
            iv_clicktosupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable
                .iv_click_to_support), Color
                .parseColor("#66ccdd"))));
        }else {
            iv_clicktosupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable
                .iv_click_to_support), Color
                .parseColor("#999999"))));
        }

        tv_clicktosupport.setText(headData.getReviewPraiseNum() + "");
        head_reviewer_img.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(headData.getReviewPic())) {
            head_reviewer_img.setImageURI(Uri.parse(headData.getReviewPic()));
        }
        head_reviewer_name.setText(headData.getReviewName());
        head_comment_content.setText(headData.getRevContent());
        head_comment_time.setText(headData.getCreateTime());
        View view_huifu = head_view.findViewById(R.id.view_huifu);
        view_huifu.setVisibility(View.VISIBLE);
    }

/*    private void refredhReplyNumber(int totalReply) {
        LaiKanEvent event = LaiKanEvent.getInstance();
        event.setEventID(LaiKanEvent.EVENT_ID_FOCUS_REFRESH_REPLY_NUMBER);
        Map<String, Object> mapEvent = new HashMap<>();
        mapEvent.put("totalreply", totalReply + "");
        mapEvent.put("replyid", replyId);
        mapEvent.put("totallikecount", null);
        mapEvent.put("isFavor", false);
        BasicApplication.postEvent(event.setEventMap(mapEvent));
    }*/

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        send_btn.setOnClickListener(this);
        tipinfo.setOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tipinfo.setLoading();
                FocusReplyDetailRequester.getReplayList(mCurrentPage, replyId, common_swiperefresh);
            }
        });
        comment_edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(comment_edit.getWindowToken(), 0);
                }
            }
        });
        comment_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                comment = comment_edit.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    send_btn.setTextColor(getResources().getColor(R.color.C_66ccdd));
                }else {
                    send_btn.setTextColor(getResources().getColor(R.color.C_333333));
                }
            }
        });

        comment_detail_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        if (END_LIST_PAGE == mCurrentPage) {
                            footer_view.setVisibility(View.VISIBLE);
                            common_swiperefresh.setLoading(false);
                        }else {
                            footer_view.setVisibility(View.GONE);
                            progressbar_modern.setShow();
                            FocusReplyDetailRequester.getReplayList(mCurrentPage, replyId, common_swiperefresh);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_btn:
                comment = comment_edit.getText().toString().trim();
                FocusReplyDetailRequester.sendReply(comment, replyId, mloadingDialog);
                break;
            case R.id.back_layout:
                comment_edit.clearFocus();
                finish();
                break;
            case R.id.rl_clicktosupport:
                if (BookFileUtils.isNoLogin()) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else if (!ActivityUitl.isNetworkAvailable(FocusCommentDetailActivity.this)) {
                    SnackBarNotice.customSnackbarShow(bottom_layout, R.string.laikan_network_anomaly);
                }else {
                    if (mIsClickToSupportSuccess) {
                        mIsClickToSupportSuccess = false;
                        FocusReplyDetailRequester.clickToSupport(rl_clicktosupport, headData.getObjectId() + "", CLICKTOSUPPORT_TYPE, LaiKanEvent.EVENT_ID_FOCUS_REFRESH_REPLY_NUMBER);
                    }
                }
                break;
            default:
                break;
        }
    }
}
